<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" type="text/css">
    <style>
      html,body,#container{
        height: 100%
      }
      .input-item{
        height: 2.2rem;
      }
      .btn{
        width: 6rem;
        /* margin: 0 1rem 0 2rem; */
      }
      .input-text{
        width: 4rem;
        margin-right:1rem;
      }
	  .amap-icon img {
            width: 25px;
            height: 34px;
        }
 
        .amap-marker-label{
            border: 0;
            background-color: transparent;
        }
	  .info{
            position: relative;
            top: 0;
            right: 0;
            min-width: 0;
        }
    </style>
	<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <title>高德框选</title>
  </head>
  <body>
    <div id='container'></div>
    <div class='info'>操作说明：圆和矩形通过拖拽来绘制，其他覆盖物通过点击来绘制</div>
    <div class="input-card" style='width: 24rem;'>
        <div class="input-item">
          <input type="hidden" name='func' value='marker'><!-- <span class="input-text">画点</span> -->
          <input type="radio" name='func' value='polyline'><span class="input-text">画折线</span>
          <input type="radio" name='func' value='polygon'><span class="input-text" style='width:5rem;'>画多边形</span>
        </div>
        <div class="input-item">
          <input type="radio" name='func' checked="checked" value='rectangle'><span class="input-text">画矩形</span>
          <input type="radio" name='func' value='circle'><span class="input-text">画圆</span>
        </div>
        <div class="input-item">
            <input id="clear" type="button" class="btn" value="清除" />
			<input id="close" type="button" class="btn" value="关闭绘图" />
			<input id="getCverlays" type="button" class="btn" value="获取覆盖物" />
        </div>
    </div>
    <script src="https://webapi.amap.com/maps?v=1.4.12&key=yourkey&plugin=AMap.MouseTool"></script>
    <script type="text/javascript">
	
    function getQueryVariable(variable){
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if(pair[0] == variable){return decodeURI(pair[1]);}
        }
        return(false);
    }

    var strs = new Array(); //定义一数组
    var str="";
    var polygons;
    var circle;
    window.onload = function () {
	    var id =  getQueryVariable("id");
	  	
	    $.ajax({
			type: "POST",	
			url: "/getMapDemo",
			data: {id:id},
			dataType:'json',
			cache: false,
			success: function(data){
				if(data.result="success"){
					
					if(data.mapDemo.mapType=="circle"){
						var center = data.mapDemo.points;
						var radius = data.mapDemo.radius;
						circle = new AMap.Circle({
						    center: new AMap.LngLat(parseFloat(center.split(",")[0]),parseFloat(center.split(",")[1])),  // 圆心位置
						    radius: radius, // 圆半径
						    fillColor:'#00b0ff',
		        	        strokeColor:'#80d8ff',
						});

						map.add(circle);
					}
	        		strs = data.mapDemo.points.split(";"); //字符分割
	        		var path = [];
	        	    for(var i=0;i<strs.length;i++){
	        	    	path.push(new AMap.LngLat(parseFloat(strs[i].split(",")[0]),parseFloat(strs[i].split(",")[1])));
	        	    	overlays.push(new AMap.LngLat(parseFloat(strs[i].split(",")[0]),parseFloat(strs[i].split(",")[1])));
	        	    }
	        	    polygons = new AMap.Polygon({
	        		    path: path,  
	        		    fillColor:'#00b0ff',
	        	        strokeColor:'#80d8ff',
	        		});
	        		map.add(polygons);
	        		map.setFitView([ polygons ]);
	        	}
			}
	 	});
    }
    //初始化地图
    var map = new AMap.Map('container',{
		resizeEnable: true, //是否监控地图容器尺寸变化
		zoom: 18, //初始地图级别
		//center: [126.947813, 44.410906], //初始地图中心点
		showIndoorMap: false //关闭室内地图
    });
    //已经图形的情况下再地图加载完成后勾画区域形状--开始
	// 多边形轮廓线的节点坐标数组
	/* var path = [
	    new AMap.LngLat(126.946684,44.411293),
	    new AMap.LngLat(126.948395,44.411293),
	    new AMap.LngLat(126.948395,44.410818),
	    new AMap.LngLat(126.946684,44.410818)
	]; */
	
	 //已经图形的情况下再地图加载完成后勾画区域形状---结束
	//工具对象
    var mouseTool = new AMap.MouseTool(map); 
    //监听draw事件可获取画好的覆盖物
    var overlays = [];
    mouseTool.on('draw',function(e){
    	var id =  getQueryVariable("id");
    	if(e.obj.CLASS_NAME=="AMap.Circle"){
    		//圆形获取坐标
    		var center = e.obj.Ce.center.lng+","+e.obj.Ce.center.lat;//圆心
    		var radius = e.obj.Ce.radius;//半径
    		//请求后台保存
			  $.ajax({
					type: "POST",	
					url: "/updateGeofenceCircle",
			    	data: {center:center,radius:radius,id:id},
					dataType:'json',
					cache: false,
					success: function(data){
						if(data.result=="success"){
							alert("围栏成功");
						}
					}
			  }); 
    	}else{
	    	var ll = e.obj.Ce.path;
			var ll = e.obj.Ce.path;
			
			for(var i=0;i<ll.length;i++){
				if(str==""){
					str+=ll[i].lng+","+ll[i].lat;
				}else{
					str+=";"+ll[i].lng+","+ll[i].lat;
				}
			 
			}
			var type = "rectangle"; 
			if(e.obj.CLASS_NAME=="AMap.Polygon"){
				type = "polygon";
			}
			//请求后台保存
			 $.ajax({
					type: "POST",	
					url: "/updateGeofence",
			    	data: {points:str,type:type,id:id},
					dataType:'json',
					cache: false,
					success: function(data){
						if(data.result=="success"){
							alert("围栏成功");
						}
					}
			 }); 
			
    	}
		
		map.remove(overlays)
        overlays = [];
        overlays.push(e.obj);
		var bounds = e.obj.getBounds();
		var allMarkers = map.getAllOverlays('marker');
		var overlayPath = [];	//覆盖物路径
        if(e.obj.CLASS_NAME=="AMap.Marker"){
			overlayPath.push(e.obj.getPosition());
	   }else{
		   var southWest = bounds.getSouthWest();
		   var northEast = bounds.getNorthEast();
		   if(southWest.equals(northEast)){
				return;
		   }
			overlayPath = e.obj.getPath();
	   }
		
    }) 
	//画图
    function draw(type){
      switch(type){
        case 'marker':{
            mouseTool.marker({
              //同Marker的Option设置
            });
            break;
        }
        case 'polyline':{
            mouseTool.polyline({
              strokeColor:'#80d8ff'
              //同Polyline的Option设置
            });
            break;
        }
        case 'polygon':{
            mouseTool.polygon({
              fillColor:'#00b0ff',
              strokeColor:'#80d8ff'
              //同Polygon的Option设置
            });
            break;
        }
        case 'rectangle':{
            mouseTool.rectangle({
              fillColor:'#00b0ff',
              strokeColor:'#80d8ff'
              //同Polygon的Option设置
            });
            break;
        }
        case 'circle':{
            mouseTool.circle({
              fillColor:'#00b0ff',
              strokeColor:'#80d8ff'
              //同Circle的Option设置
            });
            break;
        }
      }
    }
    var radios = document.getElementsByName('func');
    for(var i=0;i<radios.length;i+=1){
        radios[i].onchange = function(e){
 
          draw(e.target.value)
        }
    }
    //默认画矩形
    draw('rectangle');
	//获取所有区域覆盖物
	function getOverlays(type){
		var overlays = map.getAllOverlays(type);
		console.log(overlays);
	} 
 	//清楚覆盖物
    document.getElementById('clear').onclick = function(){
        map.remove(overlays)
        overlays = [];
        str="";
        
        map.remove(polygons);
        map.remove(circle);
		map.setFitView();
		
		
    }  
 	//关闭覆盖物
    document.getElementById('close').onclick = function(){
        mouseTool.close(true)//关闭，并清除覆盖物
		//map.clearLimitBounds();
        for(var i=0;i<radios.length;i+=1){
            radios[i].checked = false;
        }
        str="";
    }
	document.getElementById('getCverlays').onclick = function(){
        getOverlays('marker');
    }
    </script>
  </body>
</html>